package com.experienceBaby.Cashbook.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.experienceBaby.Cashbook.R;
import com.experienceBaby.Cashbook.databinding.FragmentAddBinding;
import com.experienceBaby.Cashbook.databinding.FragmentUserBinding;

import org.jetbrains.annotations.NotNull;

public class UserFragment extends Fragment {
    private FragmentUserBinding binding;
    FragmentManager manager;
    SharedPreferences SP;
    FragmentTransaction transaction;
    UserInfoFragment user;
    LoginFragment login;

    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        binding = FragmentUserBinding.inflate(inflater, container, false);
        initData();
        initView();
        return binding.getRoot();
    }

    private void initData() {
        SP = getActivity().getSharedPreferences("User", Context.MODE_PRIVATE);

    }

    private void initView() {
        transaction = getChildFragmentManager().beginTransaction();
//        String userName = SP.getString("userName", "");
        user = new UserInfoFragment(this);
        login = new LoginFragment(this);
        transaction
                .add(R.id.user_fl, user)
                .add(R.id.user_fl, login)
                .show(login)
                .hide(user)
                .commit();
        if (SP.getBoolean("isLogin", false)) {
            //已登录
            transaction
                    .show(user)
                    .hide(login);
        } else {
            transaction
                    .show(login)
                    .hide(user);
        }
    }

    public void login() {
        getChildFragmentManager().beginTransaction()
                .remove(login)
                .remove(user)
                .commit();
        user = new UserInfoFragment(this);
        getChildFragmentManager().beginTransaction().add(R.id.user_fl, user).commit();
    }

    public void logout() {
        getChildFragmentManager().beginTransaction()
                .remove(login)
                .remove(user)
                .commit();
        login = new LoginFragment(this);
        getChildFragmentManager().beginTransaction().add(R.id.user_fl, login).commit();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
